'use client'

import { generateJson, getJson, getPm2Status, reloadPm2, sqlDoctorList, stopPm2 } from "@/actions/doctor"
import { ActionSheet, Button, Card, DatePicker, Dialog, Form, Input, List, Picker, Space, SpinLoading, Tag, Toast, unstableSetRender } from 'antd-mobile'

import { CloseCircleOutline } from 'antd-mobile-icons'
import { ActionSheetShowHandler } from "antd-mobile/es/components/action-sheet"
import dayjs from "dayjs"
import { useEffect, useRef, useState } from "react"
import { createRoot } from 'react-dom/client';

unstableSetRender((node, container) => {
    container._reactRoot ||= createRoot(container);
    const root = container._reactRoot;
    root.render(node);
    return async () => {
        await new Promise((resolve) => setTimeout(resolve, 0));
        root.unmount();
    };
});
const basicColumns = new Array(24).fill(0).map((_, i) => ({
    label: `${i + 1}点`,
    value: i + 1,
}))
export default function DoctorPage() {
    const pm2Name = 'doctor_list'
    const dataid = useRef(1)

    const [visible, setVisible] = useState(false)
    const [times, setTimes] = useState<number[]>([])
    const [docId, setDocId] = useState<string>('1')
    const [docName, setDocName] = useState<string>()
    const [days, setDays] = useState<string[]>([])
    const [docList, setDocList] = useState<{ name: string; id: string, docId: string }[]>([])
    const [email, setEmail] = useState<string[]>([])
    const [status, setStatus] = useState<boolean>(true)
    const getLoadingStatus = async () => {
        const result = await getPm2Status(pm2Name)
        console.log(result);
        if (result.status === 'online') {
            setStatus(true)
        } else {
            setStatus(false)
        }
        const json = await getJson()
        if (json) {
            const temp = json
            setEmail(temp.email || [])
            setTimes(temp.time || [])
            setDays(temp.days || [])
            setDocId(temp.doctorId)
            setDocName(temp.doctor)
            dataid.current = temp.id
        }
        // setStatus(result)
    }

    const getDoctorList = async () => {
        const result = await sqlDoctorList()
        if (result) {
            setDocList(result as any)
        }
    }

    const handler = useRef<ActionSheetShowHandler>()

    useEffect(() => {
        getLoadingStatus()
        getDoctorList()
    }, [])

    const [form] = Form.useForm()

    return (
        <div>
            <div className=" text-center flex items-center justify-center flex-col my-6">

                {status && <><SpinLoading color='primary' /><div className="mt-3 mb-4 text-lg">正在抢号...</div>
                    <Button onClick={() => {
                        stopPm2(pm2Name)
                        setStatus(false)
                    }} size="small" color='danger' fill='outline'>停止抢号</Button></>}

                {!status && <div className="mt-3 mb-4 text-lg">已停止抢号 <br />
                    <Button onClick={() => {
                        reloadPm2(pm2Name)
                        setStatus(true)
                    }} size="small" color='danger' fill='outline'>开始抢号</Button>
                </div>}

            </div>
            <div>
                <List header=''>
                    <List.Item extra={docName} onClick={() => {
                        handler.current = ActionSheet.show({
                            cancelText: '取消',
                            actions: docList.map(item => {
                                return {
                                    key: item.id,
                                    text: item.name,
                                    onClick: () => {
                                        setDocName(item.name)
                                        setDocId(item.docId)
                                        handler.current?.close()
                                    }
                                }
                            }),
                            onClose: () => {
                                // Toast.show('动作面板关闭')
                            },
                        })
                    }}>
                        医生信息
                    </List.Item>
                </List>

                <Card title='整点时间' extra={
                    <Button size="mini" color='primary' fill='outline' onClick={async () => {
                        const value = await Picker.prompt({
                            columns: [basicColumns],
                        })
                        if (value) {
                            setTimes(times => [...times, Number(value)])
                        }
                    }}>添加</Button>
                }>
                    {
                        times.map((item, index) => {
                            return (
                                <Space key={item}>
                                    <Tag className="mr-2 relative" round color='#2db7f5' >
                                        <span className="text-sm px-2">{item}点</span>
                                        <span className=" absolute -right-2 -top-2" onClick={() => {
                                            setTimes(times => times.filter(i => i !== item))
                                        }}>
                                            <CloseCircleOutline style={{ fontSize: 18 }} color="black" />
                                        </span>

                                    </Tag>
                                </Space>


                            )
                        })
                    }
                </Card>
                <Card title='约号时间' extra={
                    <Button size="mini" color='primary' fill='outline' onClick={async () => {
                        setVisible(true)
                    }}>添加</Button>
                }>
                    {
                        days.map((item, index) => {
                            return (
                                <Space key={item}>
                                    <Tag className="mr-2 relative" round color='#2db7f5' >
                                        <span className="text-sm px-2">{item}</span>
                                        <span className=" absolute -right-2 -top-2" onClick={() => {
                                            setDays(days => days.filter(i => i !== item))
                                        }}>
                                            <CloseCircleOutline style={{ fontSize: 18 }} color="black" />
                                        </span>

                                    </Tag>
                                </Space>


                            )
                        })
                    }
                </Card>
                <Card title='发送邮箱' extra={
                    <Button size="mini" color='primary' fill='outline' onClick={async () => {
                        // if (form && form.resetFields) {

                        // }

                        Dialog.confirm({
                            title: "请输入",
                            content: <div>
                                <Form form={form}>
                                    <Form.Item
                                        name='email'
                                        label='邮箱'

                                        rules={[{ required: true, message: '邮箱不能为空' }]}
                                    >
                                        <Input placeholder='请输入邮箱' />
                                    </Form.Item>
                                </Form>
                            </div>,
                            onConfirm: async () => {
                                const formData = form.getFieldsValue()
                                if (formData.email.indexOf('@') == -1) {
                                    Toast.show('邮箱格式不正确')
                                } else {
                                    setEmail(email => [...email, formData.email])
                                }
                            },
                        }).then(res => {
                            form.resetFields()
                        })
                    }}>添加</Button>
                }>
                    {
                        email.map((item, index) => {
                            return (
                                <Space key={item}>
                                    <Tag className="mr-2 relative" round color='#2db7f5' >
                                        <span className="text-sm px-2">{item}</span>
                                        <span className=" absolute -right-2 -top-2" onClick={() => {
                                            setEmail(times => times.filter(i => i !== item))
                                        }}>
                                            <CloseCircleOutline style={{ fontSize: 18 }} color="black" />
                                        </span>

                                    </Tag>
                                </Space>


                            )
                        })
                    }
                </Card>
                <div className="w-[90%] m-auto mt-2">
                    <Button block color="primary" onClick={() => {
                        generateJson({
                            times,
                            days,
                            email,
                            docId,
                            docName,
                        }, dataid.current)
                        alert('保存成功')
                    }}>保存配置</Button>
                </div>

            </div>
            <DatePicker
                title='时间选择'
                visible={visible}
                onClose={() => {
                    setVisible(false)
                }}
                onConfirm={val => {
                    setDays(days => [...days, dayjs(val).format('YYYY-MM-DD')])
                }}
            />
        </div>
    )
}